#!/usr/bin/env python

#
#    Copyright (c) 2009 Corey Goldberg (corey@goldb.org)
#    License: GNU GPLv3
#
#    This file is part of PerfMetrics.
#    
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.  See the GNU General Public License 
#    for more details.
#



import os
import ConfigParser
import lib.rrd as rrd



def main():
    opts, host_infos = configure()
    
    interval = opts['interval']
    
    gauge_collectors = [
        'cpu_util', 'cpu_util_maxcore', 
        'mem_available_bytes', 'mem_cache_bytes', 'mem_committed_bytes',
        'disk_queue_length_avg', 'disk_queue_length_current',
        ]
    
    for host_info in host_infos:
        host = host_info['host']
        collectors = host_info['collectors']
        for collector in collectors:
            rrd_file = '%s_%s.rrd' % (host, collector)
            if collector in gauge_collectors:
                create_rrd(rrd_file, interval, ds_type='GAUGE')
            else:
                create_rrd(rrd_file, interval, ds_type='COUNTER')
      


def configure():
    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    opts = {}
    opts['interval'] = config.get('global', 'interval')
    host_infos = []
    for section in config.sections():
        if section != 'global':
            host_info = {}
            host_info['host'] = config.get(section, 'host')
            host_info['collectors'] = config.get(section, 'collectors').split(',')
            host_infos.append(host_info)
    return (opts, host_infos)
    


def create_rrd(rrd_file, interval, ds_type='COUNTER'):
    rrd_directory = 'db\\'
    if not os.path.exists(rrd_directory):
        os.makedirs(rrd_directory)
    if not os.path.exists(rrd_directory + rrd_file):
        rrd_db = rrd.RRD(rrd_file)
        rrd_db.rrd_exe = 'lib\\rrdtool.exe'
        rrd_db.rrd_directory = rrd_directory
        rrd_db.create(int(interval), ds_type=ds_type)
        print 'created %s%s' % (rrd_directory, rrd_file)
    else:
        print 'can not create %s%s. file already exists.' % (rrd_directory, rrd_file)
        

if __name__ == '__main__':
    main()

